import React from 'react';
import { Tree, Card, Space, Button, Input } from 'antd';
import { 
  FolderOutlined, 
  FileOutlined, 
  EyeOutlined, 
  EyeInvisibleOutlined,
  DeleteOutlined,
  CopyOutlined,
  SearchOutlined
} from '@ant-design/icons';

const { Search } = Input;

export default function StructureTree({ components = [], selectedIndex, onSelect }) {
  const [searchValue, setSearchValue] = React.useState('');
  const [expandedKeys, setExpandedKeys] = React.useState([]);
  const [autoExpandParent, setAutoExpandParent] = React.useState(true);

  // 将组件数组转换为树形结构
  const convertToTreeData = (components) => {
    return components.map((component, index) => ({
      key: index.toString(),
      title: (
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'space-between',
          width: '100%',
          padding: '4px 0'
        }}>
          <Space>
            {getComponentIcon(component.type)}
            <span style={{ 
              color: selectedIndex === index ? '#1890ff' : '#333',
              fontWeight: selectedIndex === index ? 'bold' : 'normal'
            }}>
              {component.label || component.type}
            </span>
          </Space>
          <Space size="small">
            <Button 
              type="text" 
              size="small" 
              icon={<CopyOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                // 复制功能
              }}
            />
            <Button 
              type="text" 
              size="small" 
              icon={<DeleteOutlined />}
              danger
              onClick={(e) => {
                e.stopPropagation();
                // 删除功能
              }}
            />
          </Space>
        </div>
      ),
      icon: getComponentIcon(component.type),
      children: component.children ? convertToTreeData(component.children) : undefined
    }));
  };

  // 获取组件图标
  const getComponentIcon = (type) => {
    switch (type) {
      case 'text':
        return <FileOutlined style={{ color: '#52c41a' }} />;
      case 'image':
        return <FileOutlined style={{ color: '#1890ff' }} />;
      case 'button':
        return <FileOutlined style={{ color: '#fa8c16' }} />;
      case 'input':
      case 'textarea':
      case 'select':
      case 'checkbox':
      case 'radio':
      case 'switch':
      case 'datepicker':
        return <FileOutlined style={{ color: '#722ed1' }} />;
      case 'table':
        return <FileOutlined style={{ color: '#13c2c2' }} />;
      case 'chart':
        return <FileOutlined style={{ color: '#eb2f96' }} />;
      case 'container':
      case 'row':
      case 'col':
        return <FolderOutlined style={{ color: '#faad14' }} />;
      default:
        return <FileOutlined />;
    }
  };

  // 搜索功能
  const onExpand = (newExpandedKeys) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const onChange = (e) => {
    const { value } = e.target;
    setSearchValue(value);
    
    if (value) {
      const newExpandedKeys = components
        .map((component, index) => {
          const title = component.label || component.type;
          if (title.toLowerCase().includes(value.toLowerCase())) {
            return index.toString();
          }
          return null;
        })
        .filter(key => key !== null);
      
      setExpandedKeys(newExpandedKeys);
      setAutoExpandParent(true);
    } else {
      setExpandedKeys([]);
      setAutoExpandParent(false);
    }
  };

  // 过滤树节点
  const filterTreeData = (treeData) => {
    if (!searchValue) return treeData;

    const filterNode = (node) => {
      const title = node.title.props?.children?.[0]?.props?.children?.[1]?.props?.children || '';
      if (title.toLowerCase().includes(searchValue.toLowerCase())) {
        return true;
      }
      if (node.children) {
        const filteredChildren = node.children.filter(filterNode);
        if (filteredChildren.length > 0) {
          node.children = filteredChildren;
          return true;
        }
      }
      return false;
    };

    return treeData.filter(filterNode);
  };

  const treeData = convertToTreeData(components);
  const filteredTreeData = filterTreeData(treeData);

  const handleSelect = (selectedKeys, info) => {
    if (selectedKeys.length > 0) {
      const index = parseInt(selectedKeys[0]);
      onSelect(index);
    }
  };

  return (
    <div style={{ padding: 16, height: 'calc(100vh - 200px)', overflowY: 'auto' }}>
      <Card 
        size="small" 
        title="页面结构" 
        style={{ marginBottom: 16 }}
        extra={
          <Space>
            <Button 
              type="text" 
              size="small" 
              icon={<EyeOutlined />}
              title="显示/隐藏组件"
            />
          </Space>
        }
      >
        <Search
          placeholder="搜索组件..."
          value={searchValue}
          onChange={onChange}
          style={{ marginBottom: 16 }}
          prefix={<SearchOutlined />}
        />
        
        {components.length === 0 ? (
          <div style={{ 
            textAlign: 'center', 
            color: '#999', 
            padding: 20 
          }}>
            <FolderOutlined style={{ fontSize: 48, marginBottom: 16 }} />
            <div>暂无组件</div>
            <div style={{ fontSize: 12, marginTop: 8 }}>
              从左侧添加组件到画布
            </div>
          </div>
        ) : (
          <Tree
            showIcon
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            onSelect={handleSelect}
            selectedKeys={selectedIndex !== null ? [selectedIndex.toString()] : []}
            treeData={filteredTreeData}
            style={{ background: 'transparent' }}
          />
        )}
      </Card>

      {/* 组件统计 */}
      <Card size="small" title="组件统计">
        <div style={{ fontSize: 12, color: '#666' }}>
          <div>总组件数: {components.length}</div>
          <div>选中组件: {selectedIndex !== null ? components[selectedIndex]?.label || components[selectedIndex]?.type : '无'}</div>
        </div>
      </Card>
    </div>
  );
} 